<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/blogs/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/blogs/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/blogs/css/main.css?v=5.1.3" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/blogs/images/apple-touch-icon-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/blogs/images/favicon-32x32-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/blogs/images/favicon-16x16-next.png?v=5.1.3">


  <link rel="mask-icon" href="/blogs/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="python,">





  <link rel="alternate" href="/blogs/atom.xml" title="恋恋风辰的个人博客" type="application/atom+xml">






<meta name="description" content="python中类声明如下：123456class Student(object):    def __init__(self, name, score):        self.name = name        self.score = score    def printinfo(self):        print(&apos;name is %s, score is %d&apos;%(self.nam">
<meta name="keywords" content="python">
<meta property="og:type" content="article">
<meta property="og:title" content="python学习笔记(七) 类和pygame实现打飞机游戏">
<meta property="og:url" content="https://secondtonone1.gitee.io/blogs/2017/08/22/python7/index.html">
<meta property="og:site_name" content="恋恋风辰的个人博客">
<meta property="og:description" content="python中类声明如下：123456class Student(object):    def __init__(self, name, score):        self.name = name        self.score = score    def printinfo(self):        print(&apos;name is %s, score is %d&apos;%(self.nam">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://secondtonone1.gitee.io/blogs/2017/08/22/python7/1.png">
<meta property="og:image" content="https://secondtonone1.gitee.io/blogs/2017/08/22/python7/1.jpg">
<meta property="og:updated_time" content="2020-06-22T09:30:59.084Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="python学习笔记(七) 类和pygame实现打飞机游戏">
<meta name="twitter:description" content="python中类声明如下：123456class Student(object):    def __init__(self, name, score):        self.name = name        self.score = score    def printinfo(self):        print(&apos;name is %s, score is %d&apos;%(self.nam">
<meta name="twitter:image" content="https://secondtonone1.gitee.io/blogs/2017/08/22/python7/1.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blogs/',
    scheme: 'Muse',
    version: '5.1.3',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://secondtonone1.gitee.io/blogs/2017/08/22/python7/">





  <title>python学习笔记(七) 类和pygame实现打飞机游戏 | 恋恋风辰的个人博客</title>
  








</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blogs/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">恋恋风辰的个人博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blogs/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blogs/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            Archives
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blogs/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br>
            
            Categories
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blogs/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br>
            
            Tags
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            Search
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="Searching..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://secondtonone1.gitee.io/blogs/blogs/2017/08/22/python7/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="恋恋风辰">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blogs/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="恋恋风辰的个人博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">python学习笔记(七) 类和pygame实现打飞机游戏</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2017-08-22T11:33:08+08:00">
                2017-08-22
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/blogs/categories/python/" itemprop="url" rel="index">
                    <span itemprop="name">python</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>python中<code>类声明</code>如下：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Student</span><span class="params">(object)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, name, score)</span>:</span></span><br><span class="line">        self.name = name</span><br><span class="line">        self.score = score</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">printinfo</span><span class="params">(self)</span>:</span></span><br><span class="line">        print(<span class="string">'name is %s, score is %d'</span>%(self.name, self.score))</span><br></pre></td></tr></table></figure></p>
<a id="more"></a>
<p>Student类有两个成员变量，name和score，类的成员函数第一个参数都为self，用来实现成员变量的赋值，<strong>init</strong>是类的初始化函数，初始化成员变量。</p>
<p>类的使用：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">s1 = Student(<span class="string">'niuniu'</span>,<span class="number">78</span>)</span><br><span class="line">print(s1.name)</span><br><span class="line">print(s1.score)</span><br><span class="line">s1.printinfo()</span><br><span class="line"></span><br><span class="line">s2 = Student(<span class="string">'gg'</span>,<span class="number">100</span>)</span><br><span class="line">s2.printinfo()</span><br><span class="line">s2.age = <span class="number">100</span></span><br><span class="line">print(<span class="string">'s2 age is %s'</span>%(s2.age))</span><br></pre></td></tr></table></figure>
<p>定义s2对象，并且通过s2.age=100，定义了s2的成员变量age，并且初始化为100</p>
<p>类的成员变量有两种方式定义，一个是在<strong>init</strong>函数中，一个是通过类的对象初始化。</p>
<p>类的权限设置：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Student2</span><span class="params">(object)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, name, score)</span>:</span></span><br><span class="line">        self.__name = name</span><br><span class="line">        self.__score = score</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">getname</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> self.__name</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">getscore</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> self.__score </span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">printinfo</span><span class="params">(self)</span>:</span></span><br><span class="line">        print(<span class="string">'name is %s, score is %d'</span> %(self.__name, self.__score))</span><br></pre></td></tr></table></figure>
<p><code>__name通过在变量名前边加上__表示该变量为私有变量</code>，python没有严格的权限限制，只不过通过重命名将__name变为其他的名字了，这样在外部就访问不到这个变量了。</p>
<p>通过添加getname和getscore函数获取成员变量。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">s3 = Student2(<span class="string">'s3'</span>,<span class="number">99</span>)</span><br><span class="line">s3.printinfo()</span><br><span class="line">name = s3.getname()</span><br><span class="line">print(name)</span><br><span class="line">s3.__name = <span class="string">'iloveu'</span></span><br><span class="line">print(s3.__name)</span><br><span class="line">name = s3.getname()</span><br><span class="line">print(name)</span><br><span class="line">s3.printinfo()</span><br></pre></td></tr></table></figure>
<p>虽然通过s3.<strong>name = ‘iloveu’赋值后，并没有改变类的私有变量</strong>name的数值，因为类的私有变量<strong>name的名称被改为其他的名字，用户无法知道。所以打印出的名字和s3.</strong>name数值不同。</p>
<p>python类同样支持继承</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Peaple</span><span class="params">(object)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, name)</span>:</span></span><br><span class="line">        self.__name = name</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">job</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Worker</span><span class="params">(Peaple)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">job</span><span class="params">(self)</span>:</span></span><br><span class="line">        print(<span class="string">"worker"</span>)</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Student</span><span class="params">(Peaple)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">job</span><span class="params">(self)</span>:</span></span><br><span class="line">        print(<span class="string">"student"</span>)</span><br><span class="line"></span><br><span class="line">s1 = Student(<span class="string">'student'</span>)</span><br><span class="line">s1.job</span><br><span class="line"></span><br><span class="line">w1 = Worker(<span class="string">'worker'</span>)</span><br><span class="line">w1.job</span><br><span class="line"></span><br><span class="line">p = Peaple(<span class="string">"abc"</span>)</span><br><span class="line">w = Worker(<span class="string">"abc"</span>)</span><br><span class="line">s = Student(<span class="string">"abc"</span>)</span><br></pre></td></tr></table></figure>
<p>可以通过isinstance判断类对象是否是一个类型的实例<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">print(isinstance(p, Peaple))</span><br><span class="line">print(isinstance(w,Peaple))</span><br><span class="line">print(isinstance(s,Peaple))</span><br><span class="line">print(isinstance(s,Worker))</span><br><span class="line">print(isinstance(p,Student))</span><br></pre></td></tr></table></figure></p>
<p><code>子类对象是基类类型的实例，而基类对象不一定是子类类型的实例</code>。比如Student继承于Peaple，学生是人，但是人不一定是学生。</p>
<p>类的属性控制：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Designer</span><span class="params">(Worker)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self,name,age)</span>:</span></span><br><span class="line">        self.__name = name</span><br><span class="line">        self.age = age</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">job</span><span class="params">(self)</span>:</span></span><br><span class="line">        print(<span class="string">"Designer"</span>)</span><br><span class="line"></span><br><span class="line">designer = Designer(<span class="string">'David'</span>,<span class="number">18</span>)</span><br></pre></td></tr></table></figure>
<p>获取属性，设置属性，判断是否含有某个属性</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#判断类中是否有某个实例print(hasattr(designer, 'age') )</span></span><br><span class="line">print(hasattr(designer,<span class="string">'job'</span>))</span><br><span class="line">print(hasattr(designer,<span class="string">'name'</span>))</span><br><span class="line"></span><br><span class="line"><span class="comment">#设置sex属性，属性值为'female'</span></span><br><span class="line">setattr(designer, <span class="string">'sex'</span>, <span class="string">'female'</span>)</span><br><span class="line"></span><br><span class="line">print(designer.sex)</span><br><span class="line"></span><br><span class="line"><span class="comment">#获取job属性，返回值为job函数对象</span></span><br><span class="line">fn = getattr(designer, <span class="string">'job'</span>)</span><br><span class="line"><span class="comment">#调用fn函数</span></span><br><span class="line">fn()</span><br></pre></td></tr></table></figure>
<p><code>类的公有属性，为所有对象共有</code>，类似于C++的static成员变量</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#通过self变量或者实例自身可以实现实例属性绑定</span></span><br><span class="line"><span class="comment">#在类中直接定义一个变量，这个属性归类所有，类似于C++的static变量。</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Temple</span><span class="params">(object)</span>:</span></span><br><span class="line">    staticmember = <span class="number">1000</span></span><br><span class="line"></span><br><span class="line">temp1 = Temple()</span><br><span class="line"><span class="comment">#temp1没有自身属性成员staticmember，</span></span><br><span class="line"><span class="comment">#而Temple类含有共享属性</span></span><br><span class="line"><span class="comment">#下面这种方式打印的是类的共有属性</span></span><br><span class="line">print(temp1.staticmember)</span><br><span class="line"><span class="comment">#为实例temp1绑定其自身的成员staticmember</span></span><br><span class="line"><span class="comment">#并且设置数值为2048</span></span><br><span class="line">temp1.staticmember = <span class="number">2048</span></span><br><span class="line"><span class="comment">#打印实例temp1的成员staticmember</span></span><br><span class="line">print(temp1.staticmember)</span><br><span class="line"><span class="comment">#打印类的共享成员</span></span><br><span class="line">print(Temple.staticmember)</span><br><span class="line"><span class="comment">#删除实例的属性staticmember</span></span><br><span class="line"><span class="keyword">del</span> temp1.staticmember</span><br><span class="line"><span class="comment">#打印出类共享的属性</span></span><br><span class="line">print(temp1.staticmember)</span><br></pre></td></tr></table></figure>
<p>可以为类绑定成员函数，也可以只为类的一个实例绑定成员函数</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">setage</span><span class="params">(self, age)</span>:</span></span><br><span class="line">    self.__age = age</span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">getage</span><span class="params">(self)</span>:</span></span><br><span class="line">    <span class="keyword">return</span> self.__age</span><br><span class="line"><span class="comment">###给实例绑定方法</span></span><br><span class="line">temp1.setage = MethodType(setage, temp1)</span><br><span class="line">temp1.getage = MethodType(getage,temp1)</span><br><span class="line">temp1.setage(<span class="number">125</span>)</span><br><span class="line">print(temp1.getage())</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">setname</span><span class="params">(self, name)</span>:</span></span><br><span class="line">    self.__name = name</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">getname</span><span class="params">(self)</span>:</span></span><br><span class="line">    <span class="keyword">return</span> self.__name</span><br><span class="line"></span><br><span class="line"><span class="comment">#给类绑定方法</span></span><br><span class="line">Temple.setname= setname</span><br><span class="line">Temple.getname = getname</span><br><span class="line"></span><br><span class="line">temp2 = Temple()</span><br><span class="line">temp2.setname(<span class="string">'name'</span>)</span><br><span class="line">print(temp2.getname())</span><br></pre></td></tr></table></figure>
<p>可以通过@property的方式，通过属性访问的方式就可以调用函数</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Definetion</span><span class="params">(object)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, member)</span>:</span></span><br><span class="line">        self.__member = member</span><br><span class="line"><span class="meta">    @property</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">member</span><span class="params">(self)</span>:</span></span><br><span class="line">        print(<span class="string">"call getter"</span>)</span><br><span class="line">        <span class="keyword">return</span> self.__member</span><br><span class="line"><span class="meta">    @member.setter</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">member</span><span class="params">(self, member)</span>:</span></span><br><span class="line">        print(<span class="string">"call setter"</span>)</span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> isinstance(member,int):</span><br><span class="line">            <span class="keyword">raise</span> TypeError(<span class="string">"member must be int type"</span>)</span><br><span class="line">        self.__member = member</span><br><span class="line"><span class="meta">    @member.deleter</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">member</span><span class="params">(self)</span>:</span></span><br><span class="line">        print(<span class="string">"call deleter"</span>)</span><br><span class="line">        <span class="keyword">raise</span> AttributeError(<span class="string">"Cann't delete member"</span>)</span><br><span class="line"></span><br><span class="line">definetioner = Definetion(<span class="number">3</span>)</span><br><span class="line">print(definetioner.member)</span><br><span class="line">definetioner.member = <span class="number">1024</span></span><br><span class="line">print(definetioner.member)</span><br></pre></td></tr></table></figure>
<p>将member分别实现为返回属性<strong>member，设置</strong>member，以及删除__member的函数。在每个member上添加对应格式的@property，@member.setter， @member.deleter。</p>
<p>通过属性访问的方式就可以调用对应的函数， definetioner.member返回<strong>member值,  definetioner</strong>member = 1024调用设置__member的函数。deleter definetioner.member调用的是删除函数。</p>
<h2 id="实战：用pygame库做一个打飞机的小游戏"><a href="#实战：用pygame库做一个打飞机的小游戏" class="headerlink" title="实战：用pygame库做一个打飞机的小游戏"></a>实战：用pygame库做一个打飞机的小游戏</h2><p><code>pygame是python的一个做游戏的库</code>，安装方法自行百度。</p>
<p>实现子弹类</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 设置游戏屏幕大小</span></span><br><span class="line">SCREEN_WIDTH = <span class="number">480</span></span><br><span class="line">SCREEN_HEIGHT = <span class="number">800</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 子弹类</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Bullet</span><span class="params">(pygame.sprite.Sprite)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, bullet_img, init_pos)</span>:</span></span><br><span class="line">        pygame.sprite.Sprite.__init__(self)</span><br><span class="line">        self.image = bullet_img</span><br><span class="line">        self.rect = self.image.get_rect()</span><br><span class="line">        self.rect.midbottom = init_pos</span><br><span class="line">        self.speed = <span class="number">10</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">move</span><span class="params">(self)</span>:</span></span><br><span class="line">        self.rect.top -= self.speed</span><br></pre></td></tr></table></figure>
<p>写玩家的飞机类</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 玩家飞机类</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Player</span><span class="params">(pygame.sprite.Sprite)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, plane_img, player_rect, init_pos)</span>:</span></span><br><span class="line">        pygame.sprite.Sprite.__init__(self)</span><br><span class="line">        self.image = []                                 <span class="comment"># 用来存储玩家飞机图片的列表</span></span><br><span class="line">        <span class="keyword">for</span> i <span class="keyword">in</span> range(len(player_rect)):</span><br><span class="line">            self.image.append(plane_img.subsurface(player_rect[i]).convert_alpha())</span><br><span class="line">        self.rect = player_rect[<span class="number">0</span>]                      <span class="comment"># 初始化图片所在的矩形</span></span><br><span class="line">        self.rect.topleft = init_pos                    <span class="comment"># 初始化矩形的左上角坐标</span></span><br><span class="line">        self.speed = <span class="number">8</span>                                  <span class="comment"># 初始化玩家飞机速度，这里是一个确定的值</span></span><br><span class="line">        self.bullets = pygame.sprite.Group()            <span class="comment"># 玩家飞机所发射的子弹的集合</span></span><br><span class="line">        self.img_index = <span class="number">0</span>                              <span class="comment"># 玩家飞机图片索引</span></span><br><span class="line">        self.is_hit = <span class="keyword">False</span>                             <span class="comment"># 玩家是否被击中</span></span><br></pre></td></tr></table></figure>
<p>实现飞机类的几个功能函数</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 发射子弹</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">shoot</span><span class="params">(self, bullet_img)</span>:</span></span><br><span class="line">        bullet = Bullet(bullet_img, self.rect.midtop)</span><br><span class="line">        self.bullets.add(bullet)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 向上移动，需要判断边界</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">moveUp</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">if</span> self.rect.top &lt;= <span class="number">0</span>:</span><br><span class="line">            self.rect.top = <span class="number">0</span></span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            self.rect.top -= self.speed</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 向下移动，需要判断边界</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">moveDown</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">if</span> self.rect.top &gt;= SCREEN_HEIGHT - self.rect.height:</span><br><span class="line">            self.rect.top = SCREEN_HEIGHT - self.rect.height</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            self.rect.top += self.speed</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 向左移动，需要判断边界</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">moveLeft</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">if</span> self.rect.left &lt;= <span class="number">0</span>:</span><br><span class="line">            self.rect.left = <span class="number">0</span></span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            self.rect.left -= self.speed</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 向右移动，需要判断边界        </span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">moveRight</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">if</span> self.rect.left &gt;= SCREEN_WIDTH - self.rect.width:</span><br><span class="line">            self.rect.left = SCREEN_WIDTH - self.rect.width</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            self.rect.left += self.speed</span><br></pre></td></tr></table></figure>
<p>实现敌方飞机类</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 敌机类</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Enemy</span><span class="params">(pygame.sprite.Sprite)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, enemy_img, enemy_down_imgs, init_pos)</span>:</span></span><br><span class="line">       pygame.sprite.Sprite.__init__(self)</span><br><span class="line">       self.image = enemy_img</span><br><span class="line">       self.rect = self.image.get_rect()</span><br><span class="line">       self.rect.topleft = init_pos</span><br><span class="line">       self.down_imgs = enemy_down_imgs</span><br><span class="line">       self.speed = <span class="number">2</span></span><br><span class="line">       self.down_index = <span class="number">0</span></span><br><span class="line"></span><br><span class="line">    <span class="comment"># 敌机移动，边界判断及删除在游戏主循环里处理</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">move</span><span class="params">(self)</span>:</span></span><br><span class="line">        self.rect.top += self.speed</span><br></pre></td></tr></table></figure>
<p>实现游戏主逻辑</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 初始化 pygame</span></span><br><span class="line">pygame.init()</span><br><span class="line"></span><br><span class="line"><span class="comment"># 设置游戏界面大小、背景图片及标题</span></span><br><span class="line"><span class="comment"># 游戏界面像素大小</span></span><br><span class="line">screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))</span><br><span class="line"></span><br><span class="line"><span class="comment"># 游戏界面标题</span></span><br><span class="line">pygame.display.set_caption(<span class="string">'飞机大战'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 背景图</span></span><br><span class="line">background = pygame.image.load(<span class="string">'resources/image/background.png'</span>).convert()</span><br><span class="line"></span><br><span class="line"><span class="comment"># Game Over 的背景图</span></span><br><span class="line">game_over = pygame.image.load(<span class="string">'resources/image/gameover.png'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 飞机及子弹图片集合</span></span><br><span class="line">plane_img = pygame.image.load(<span class="string">'resources/image/shoot.png'</span>)</span><br></pre></td></tr></table></figure>
<p>由于资源采用大图的方式，敌机和飞机，子弹都绘制在一站图片上，需要裁剪，pygame提供裁剪函数</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 设置玩家飞机不同状态的图片列表，多张图片展示为动画效果</span></span><br><span class="line">player_rect = []</span><br><span class="line">player_rect.append(pygame.Rect(<span class="number">0</span>, <span class="number">99</span>, <span class="number">102</span>, <span class="number">126</span>))        <span class="comment"># 玩家飞机图片</span></span><br><span class="line">player_rect.append(pygame.Rect(<span class="number">165</span>, <span class="number">360</span>, <span class="number">102</span>, <span class="number">126</span>))</span><br><span class="line">player_rect.append(pygame.Rect(<span class="number">165</span>, <span class="number">234</span>, <span class="number">102</span>, <span class="number">126</span>))     <span class="comment"># 玩家爆炸图片</span></span><br><span class="line">player_rect.append(pygame.Rect(<span class="number">330</span>, <span class="number">624</span>, <span class="number">102</span>, <span class="number">126</span>))</span><br><span class="line">player_rect.append(pygame.Rect(<span class="number">330</span>, <span class="number">498</span>, <span class="number">102</span>, <span class="number">126</span>))</span><br><span class="line">player_rect.append(pygame.Rect(<span class="number">432</span>, <span class="number">624</span>, <span class="number">102</span>, <span class="number">126</span>))</span><br><span class="line">player_pos = [<span class="number">200</span>, <span class="number">600</span>]</span><br><span class="line">player = Player(plane_img, player_rect, player_pos)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 子弹图片</span></span><br><span class="line">bullet_rect = pygame.Rect(<span class="number">1004</span>, <span class="number">987</span>, <span class="number">9</span>, <span class="number">21</span>)</span><br><span class="line">bullet_img = plane_img.subsurface(bullet_rect)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 敌机不同状态的图片列表，多张图片展示为动画效果</span></span><br><span class="line">enemy1_rect = pygame.Rect(<span class="number">534</span>, <span class="number">612</span>, <span class="number">57</span>, <span class="number">43</span>)</span><br><span class="line">enemy1_img = plane_img.subsurface(enemy1_rect)</span><br><span class="line">enemy1_down_imgs = []</span><br><span class="line">enemy1_down_imgs.append(plane_img.subsurface(pygame.Rect(<span class="number">267</span>, <span class="number">347</span>, <span class="number">57</span>, <span class="number">43</span>)))</span><br><span class="line">enemy1_down_imgs.append(plane_img.subsurface(pygame.Rect(<span class="number">873</span>, <span class="number">697</span>, <span class="number">57</span>, <span class="number">43</span>)))</span><br><span class="line">enemy1_down_imgs.append(plane_img.subsurface(pygame.Rect(<span class="number">267</span>, <span class="number">296</span>, <span class="number">57</span>, <span class="number">43</span>)))</span><br><span class="line">enemy1_down_imgs.append(plane_img.subsurface(pygame.Rect(<span class="number">930</span>, <span class="number">697</span>, <span class="number">57</span>, <span class="number">43</span>)))</span><br></pre></td></tr></table></figure>
<p>管理敌机和敌机被击中的等对象</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#存储敌机，管理多个对象</span></span><br><span class="line">enemies1 = pygame.sprite.Group()</span><br><span class="line"></span><br><span class="line"><span class="comment"># 存储被击毁的飞机，用来渲染击毁动画</span></span><br><span class="line">enemies_down = pygame.sprite.Group()</span><br><span class="line"></span><br><span class="line"><span class="comment"># 初始化射击及敌机移动频率</span></span><br><span class="line">shoot_frequency = <span class="number">0</span></span><br><span class="line">enemy_frequency = <span class="number">0</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 玩家飞机被击中后的效果处理</span></span><br><span class="line">player_down_index = <span class="number">16</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 初始化分数</span></span><br><span class="line">score = <span class="number">0</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 游戏循环帧率设置</span></span><br><span class="line">clock = pygame.time.Clock()</span><br><span class="line"></span><br><span class="line"><span class="comment"># 判断游戏循环退出的参数</span></span><br><span class="line">running = <span class="keyword">True</span></span><br></pre></td></tr></table></figure>
<p>通过循环控制游戏逻辑，不断生成敌机和子弹，刷新场景等。</p>
<p>给大家个建议，也是忠告，pygame实现的游戏循环体中一定要捕捉事件消息，不然会因为死循环而一直卡顿，甚至崩溃。先实现循环体中事件捕捉</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 游戏主循环</span></span><br><span class="line"><span class="keyword">while</span> running:</span><br><span class="line">    <span class="comment"># 控制游戏最大帧率为 60</span></span><br><span class="line">    clock.tick(<span class="number">60</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 更新屏幕</span></span><br><span class="line">    pygame.display.update()</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 处理游戏退出</span></span><br><span class="line">    <span class="keyword">for</span> event <span class="keyword">in</span> pygame.event.get():</span><br><span class="line">        <span class="keyword">if</span> event.type == pygame.QUIT:</span><br><span class="line">            pygame.quit()</span><br><span class="line">            exit()</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 获取键盘事件（上下左右按键）</span></span><br><span class="line">    key_pressed = pygame.key.get_pressed()</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 处理键盘事件（移动飞机的位置）</span></span><br><span class="line">    <span class="keyword">if</span> key_pressed[K_w] <span class="keyword">or</span> key_pressed[K_UP]:</span><br><span class="line">        player.moveUp()</span><br><span class="line">    <span class="keyword">if</span> key_pressed[K_s] <span class="keyword">or</span> key_pressed[K_DOWN]:</span><br><span class="line">        player.moveDown()</span><br><span class="line">    <span class="keyword">if</span> key_pressed[K_a] <span class="keyword">or</span> key_pressed[K_LEFT]:</span><br><span class="line">        player.moveLeft()</span><br><span class="line">    <span class="keyword">if</span> key_pressed[K_d] <span class="keyword">or</span> key_pressed[K_RIGHT]:</span><br><span class="line">        player.moveRight()</span><br></pre></td></tr></table></figure>
<p>在while running循环中添加子弹和敌机生成逻辑</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 生成子弹，需要控制发射频率</span></span><br><span class="line">    <span class="comment"># 首先判断玩家飞机没有被击中</span></span><br><span class="line">    <span class="keyword">if</span> <span class="keyword">not</span> player.is_hit:</span><br><span class="line">        <span class="keyword">if</span> shoot_frequency % <span class="number">15</span> == <span class="number">0</span>:</span><br><span class="line">            player.shoot(bullet_img)</span><br><span class="line">        shoot_frequency += <span class="number">1</span></span><br><span class="line">        <span class="keyword">if</span> shoot_frequency &gt;= <span class="number">15</span>:</span><br><span class="line">            shoot_frequency = <span class="number">0</span></span><br><span class="line"></span><br><span class="line">    <span class="comment"># 生成敌机，需要控制生成频率</span></span><br><span class="line">    <span class="keyword">if</span> enemy_frequency % <span class="number">50</span> == <span class="number">0</span>:</span><br><span class="line">        enemy1_pos = [random.randint(<span class="number">0</span>, SCREEN_WIDTH - enemy1_rect.width), <span class="number">0</span>]</span><br><span class="line">        enemy1 = Enemy(enemy1_img, enemy1_down_imgs, enemy1_pos)</span><br><span class="line">        enemies1.add(enemy1)</span><br><span class="line">    enemy_frequency += <span class="number">1</span></span><br><span class="line">    <span class="keyword">if</span> enemy_frequency &gt;= <span class="number">100</span>:</span><br><span class="line">        enemy_frequency = <span class="number">0</span></span><br></pre></td></tr></table></figure>
<p>在while running循环中子弹和敌机移动逻辑</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> bullet <span class="keyword">in</span> player.bullets:</span><br><span class="line">        <span class="comment"># 以固定速度移动子弹</span></span><br><span class="line">        bullet.move()</span><br><span class="line">        <span class="comment"># 移动出屏幕后删除子弹</span></span><br><span class="line">        <span class="keyword">if</span> bullet.rect.bottom &lt; <span class="number">0</span>:</span><br><span class="line">            player.bullets.remove(bullet)   </span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> enemy <span class="keyword">in</span> enemies1:</span><br><span class="line">        <span class="comment">#2. 移动敌机</span></span><br><span class="line">        enemy.move()</span><br><span class="line">        <span class="comment">#3. 敌机与玩家飞机碰撞效果处理</span></span><br><span class="line">        <span class="keyword">if</span> pygame.sprite.collide_circle(enemy, player):</span><br><span class="line">            enemies_down.add(enemy)</span><br><span class="line">            enemies1.remove(enemy)</span><br><span class="line">            player.is_hit = <span class="keyword">True</span></span><br><span class="line">            <span class="keyword">break</span></span><br><span class="line">        <span class="comment">#4. 移动出屏幕后删除飞机    </span></span><br><span class="line">        <span class="keyword">if</span> enemy.rect.top &lt; <span class="number">0</span>:</span><br><span class="line">            enemies1.remove(enemy)</span><br><span class="line"></span><br><span class="line">    <span class="comment">#敌机被子弹击中效果处理</span></span><br><span class="line">    <span class="comment"># 将被击中的敌机对象添加到击毁敌机 Group 中，用来渲染击毁动画</span></span><br><span class="line">    enemies1_down = pygame.sprite.groupcollide(enemies1, player.bullets, <span class="number">1</span>, <span class="number">1</span>)</span><br><span class="line">    <span class="keyword">for</span> enemy_down <span class="keyword">in</span> enemies1_down:</span><br><span class="line">        enemies_down.add(enemy_down)</span><br></pre></td></tr></table></figure>
<p>在while running循环中添加自己飞机动态逻辑</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 绘制玩家飞机</span></span><br><span class="line">    <span class="keyword">if</span> <span class="keyword">not</span> player.is_hit:</span><br><span class="line">        screen.blit(player.image[player.img_index], player.rect)</span><br><span class="line">        <span class="comment"># 更换图片索引使飞机有动画效果</span></span><br><span class="line">        player.img_index = shoot_frequency // <span class="number">8</span></span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        <span class="comment"># 玩家飞机被击中后的效果处理</span></span><br><span class="line">        player.img_index = player_down_index // <span class="number">8</span></span><br><span class="line">        screen.blit(player.image[player.img_index], player.rect)</span><br><span class="line">        player_down_index += <span class="number">1</span></span><br><span class="line">        <span class="keyword">if</span> player_down_index &gt; <span class="number">47</span>:</span><br><span class="line">            <span class="comment"># 击中效果处理完成后游戏结束</span></span><br><span class="line">            running = <span class="keyword">False</span></span><br><span class="line"></span><br><span class="line">    <span class="comment"># 敌机被子弹击中效果显示</span></span><br><span class="line">    <span class="keyword">for</span> enemy_down <span class="keyword">in</span> enemies_down:</span><br><span class="line">        <span class="keyword">if</span> enemy_down.down_index == <span class="number">0</span>:</span><br><span class="line">            <span class="keyword">pass</span></span><br><span class="line">        <span class="keyword">if</span> enemy_down.down_index &gt; <span class="number">7</span>:</span><br><span class="line">            enemies_down.remove(enemy_down)</span><br><span class="line">            score += <span class="number">1000</span></span><br><span class="line">            <span class="keyword">continue</span></span><br><span class="line">        screen.blit(enemy_down.down_imgs[enemy_down.down_index // <span class="number">2</span>], enemy_down.rect)</span><br><span class="line">        enemy_down.down_index += <span class="number">1</span></span><br></pre></td></tr></table></figure>
<p>效果显示：<br><img src="1.png" alt="1.png"><br>源码下载地址：<a href="https://github.com/secondtonone1/python-/tree/master/plane" target="_blank" rel="noopener">打飞机小游戏python</a></p>
<p>谢谢关注我的公众号：<br><img src="1.jpg" alt="1.jpg"></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blogs/tags/python/" rel="tag"># python</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blogs/2017/08/22/python6/" rel="next" title="python学习笔记(六) 函数式编程">
                <i class="fa fa-chevron-left"></i> python学习笔记(六) 函数式编程
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blogs/2017/08/24/hexoblogs/" rel="prev" title="使用hexo搭建个人博客">
                使用hexo搭建个人博客 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">恋恋风辰</p>
              <p class="site-description motion-element" itemprop="description">重剑无锋，大巧不工</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blogs/archives/">
              
                  <span class="site-state-item-count">146</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blogs/categories/index.html">
                  <span class="site-state-item-count">11</span>
                  <span class="site-state-item-name">categories</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blogs/tags/index.html">
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">tags</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/blogs/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          <div class="links-of-author motion-element">
            
              
                <span class="links-of-author-item">
                  <a href="https://github.com/secondtonone1" target="_blank" title="GitHub">
                    
                      <i class="fa fa-fw fa-github"></i>GitHub</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.zhihu.com/people/wang-wu-chen-32/activities" target="_blank" title="ZhiHu">
                    
                      <i class="fa fa-fw fa-ZhiHu"></i>ZhiHu</a>
                </span>
              
            
          </div>

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#实战：用pygame库做一个打飞机的小游戏"><span class="nav-number">1.</span> <span class="nav-text">实战：用pygame库做一个打飞机的小游戏</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">恋恋风辰</span>

  
  
 
    <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span id="busuanzi_container_site_pv">本站总访问量<span id="busuanzi_value_site_pv"></span>次</span>
    <span class="post-meta-divider">|</span>
    <span id="busuanzi_container_site_uv">本站访客数<span id="busuanzi_value_site_uv"></span>人</span>
 
 
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.3</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blogs/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blogs/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/blogs/js/src/motion.js?v=5.1.3"></script>



  
  

  
  <script type="text/javascript" src="/blogs/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/blogs/js/src/post-details.js?v=5.1.3"></script>



  


  <script type="text/javascript" src="/blogs/js/src/bootstrap.js?v=5.1.3"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blogs/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
